<template>
  <div style="background-color: rgba(239, 250, 251, 1); padding: 20px; border-radius: 8px;">
    <a-card style=" padding: 10px;  border-radius: 4px;">
        <!-- 查询表单 -->
        <div style=" width: 100%;">
          <a-form :form="searchForm">
            <a-row :gutter="16" style="flex-wrap: wrap;">
              <a-col :md="4" :sm="24">
                <a-form-item label="专家姓名" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
                  <a-input v-model="searchParams.talentRealName" @pressEnter="search"/>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="研究领域" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
                  <a-select v-model="searchParams.talentGwFields" allowClear>
                    <a-select-option v-for="item in fieldsArr" :value="item">
                      {{ item }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <a-form-item label="职称" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
                  <a-select v-model="searchParams.talentJobTitle" style="width: 100%;" allowClear>
                    <a-select-option value="院士">院士</a-select-option>
                    <a-select-option value="正高">正高</a-select-option>
                    <a-select-option value="副高">副高</a-select-option>
                    <a-select-option value="中级">中级</a-select-option>
                    <a-select-option value="初级">初级</a-select-option>
                    <a-select-option value="">其他</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <a-form-item label="职务" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
                  <a-input v-model="searchParams.talentJobLevel"  @pressEnter="search"/>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <a-form-item label="工作单位" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
                  <a-input v-model="searchParams.talentCompany"  @pressEnter="search"/>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <a-form-item label="成果名称" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
                  <a-input v-model="searchParams.fruitName"  @pressEnter="search"/>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24" >
                <a-form-item label="合作次数" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
                  <a-input-number v-model="searchParams.coMinNum" :min="0"/>
                  —
                  <a-input-number v-model="searchParams.coMaxNum" :min="searchParams.coMinNum == null ? 0 : searchParams.coMinNum"/>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="24">
                  <a-button type="primary" @click="search">查询</a-button>
                  <a-button type="primary" ghost @click="reset" style="margin-left: 10px;">重置</a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <div style="text-align: right; margin-bottom: 10px;">
          <a-button type="primary" @click="showModal('add')" v-gw-permission="'nd_expert_add'">新增</a-button>&nbsp;&nbsp;
          <a-button type="primary" @click="showImportModal()" v-gw-permission="'nd_expert_import'">批量导入</a-button>&nbsp;&nbsp;
          <a-button type="primary" @click="showStandard()" v-gw-permission="'nd_expert_examine'">查看数据标准</a-button>&nbsp;&nbsp;
          <a-button type="primary" @click="showEvaIndex()" v-gw-permission="'nd_expert_examine'">查看指标管理</a-button>&nbsp;&nbsp;
          <a-button type="default" @click="showChart()" v-gw-permission="'nd_expert_statistics'">展示统计图表</a-button>&nbsp;&nbsp;
          <!--            <a-button type="danger" :loading="mergeLoading" @click="merge()">合并</a-button>-->
        </div>
        <!-- 列表展示 -->
        <a-table :columns="columns" :dataSource="dataSource" :loading="loading" :key="tableKey" :pagination="false">
          <a slot="talentFruitCount" slot-scope="text,record" @click="lookFruit(record)">{{ text == null ? 0 : text }}</a>
          <template slot="action" slot-scope="text, record">
            <a-button @click="edit(record)" v-gw-permission="'nd_expert_edit'">编辑</a-button>&nbsp;
            <a-popconfirm
              title="是否确认删除此条数据?"
              ok-text="是"
              cancel-text="否"
              @confirm="remove(record)"
            >
              <a-button type="danger" v-gw-permission="'nd_expert_delete'">删除</a-button>
            </a-popconfirm>
            &nbsp;&nbsp;
<!--            <a-button type="primary" @click="lookFruit(record)">查看成果</a-button>-->
          </template>
        </a-table>
        <br />
        <!-- 分页器 -->
        <a-pagination :show-total="total => `共${total}条`" :total="total" :current="pagination.current"
                      :pageSize="pagination.pageSize" @change="handlePaginationChange" />
    </a-card>
    <!-- 新增/编辑对话框 -->
    <a-modal v-model="modal.visible" :title="modal.title" @ok="handleOk" @cancel="handleCancel" width="800px">
      <!-- 表单项 -->
      <a-form :form="modalForm" :label-col="{ span: 8 }" :wrapper-col="{ span: 12 }">
        <!-- 表单项 -->
        <a-form-item label="姓名" :required="true" :rules="[ { required: true, message: '请输入姓名' } ]">
          <a-input v-model="modal.formData.talentRealName" />
        </a-form-item>
        <a-form-item label="照片">
          <a-upload
            name="avatar"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :before-upload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="imageUrl" :src="imageUrl" alt="avatar" style="height: 100px; width: 100px;" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="手机号">
          <a-input v-model="modal.formData.talentAllPhoneNumber" />
        </a-form-item>
        <a-form-item label="所属单位" :required="true" :rules="[ { required: true, message: '请输入所属单位' } ]">
          <a-input v-model="modal.formData.talentCompany" />
        </a-form-item>
        <a-form-item label="研究领域">
          <a-select v-model="modal.formData.talentGwFields">
            <a-select-option v-for="item in fieldsArr" :value="item">
              {{ item }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="职称">
          <a-select default-value="1" v-model="modal.formData.talentJobTitle">
            <a-select-option value="院士">院士</a-select-option>
            <a-select-option value="正高">正高</a-select-option>
            <a-select-option value="副高">副高</a-select-option>
            <a-select-option value="中级">中级</a-select-option>
            <a-select-option value="初级">初级</a-select-option>
            <a-select-option value="其他">其他</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="职务">
          <a-input v-model="modal.formData.talentJobLevel" />
          <!--          <a-select default-value="1" v-model="modal.formData.talentJobLevel">-->
          <!--            <a-select-option value="基础员">基础员</a-select-option>-->
          <!--            <a-select-option value="助理工程师">助理工程师</a-select-option>-->
          <!--            <a-select-option value="中级工程师">中级工程师</a-select-option>-->
          <!--            <a-select-option value="高级工程师">高级工程师</a-select-option>-->
          <!--            <a-select-option value="正高级工程师">正高级工程师</a-select-option>-->
          <!--            <a-select-option value="初级经济师">初级经济师</a-select-option>-->
          <!--            <a-select-option value="中级经济师">中级经济师</a-select-option>-->
          <!--            <a-select-option value="高级经济师">高级经济师</a-select-option>-->
          <!--            <a-select-option value="助理研究员">助理研究员</a-select-option>-->
          <!--            <a-select-option value="副研究员">副研究员</a-select-option>-->
          <!--            <a-select-option value="研究员">研究员</a-select-option>-->
          <!--            <a-select-option value="讲师">讲师</a-select-option>-->
          <!--            <a-select-option value="副教授">副教授</a-select-option>-->
          <!--            <a-select-option value="教授">教授</a-select-option>-->
          <!--          </a-select>-->
        </a-form-item>
        <a-form-item label="性别">
          <a-select default-value="男" v-model="modal.formData.talentGender">
            <a-select-option value="男">男</a-select-option>
            <a-select-option value="女">女</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="身份证号">
          <a-input v-model="modal.formData.talentIdNum" />
        </a-form-item>
        <a-form-item label="邮箱">
          <a-input v-model="modal.formData.talentEmail" />
        </a-form-item>
<!--        <a-form-item label="合作次数">-->
<!--          <a-input-number size="small" v-model="modal.formData.talentCooperationNum" :min="1"></a-input-number>-->
<!--        </a-form-item>-->
        <a-form-item label="简介">
          <a-textarea v-model="modal.formData.talentIntro" />
        </a-form-item>
        <!--                <a-form-item label="国籍">-->
        <!--                    <a-input v-model="modal.formData.nationality" />-->
        <!--                </a-form-item>-->
        <!--                <a-form-item label="政治面貌">-->
        <!--                    <a-input v-model="modal.formData.politicsStatus" />-->
        <!--                </a-form-item>-->
      </a-form>
    </a-modal>

    <!-- 新增/编辑对话框 -->
    <a-modal v-model="mergeModal.visible" :title="mergeModal.title" @ok="handleMergeOk" @cancel="handleMergeCancel"
             width="800px">
      数据合并入：
      <a-select style="width: 100%" @change="handleMergeChange">
        <a-select-option v-for="item in selectedRows" :value="item.id">
          {{ item.realName }}-{{ item.company }}
        </a-select-option>
      </a-select>
    </a-modal>

    <!-- 展示图表 -->
    <a-modal v-model="showChartForm" title="图表统计" width="850px" :footer="null">
      <div>统计范围：
        <template>
          <div class="search-result-card">
            <span class="result-item">
              <span class="label">专家名称：</span>
              <span v-if="searchParams.talentRealName" class="value">
                <strong>{{ searchParams.talentRealName }}</strong>
              </span>
              <span v-else class="value-empty">空</span>
            </span>

            <span class="result-item">
              <span class="label">研究领域：</span>
              <span v-if="searchParams.talentGwFields" class="value">
                <strong>{{ searchParams.talentGwFields }}</strong>
              </span>
              <span v-else class="value-empty">空</span>
            </span>

            <span class="result-item">
              <span class="label">职称：</span>
              <span v-if="searchParams.talentJobTitle" class="value">
                <strong>{{ searchParams.talentJobTitle }}</strong>
              </span>
              <span v-else class="value-empty">空</span>
            </span>

            <span class="result-item">
              <span class="label">职务：</span>
              <span v-if="searchParams.talentJobLevel" class="value">
                <strong>{{ searchParams.talentJobLevel }}</strong>
              </span>
              <span v-else class="value-empty">空</span>
            </span>

            <span class="result-item">
              <span class="label">工作单位：</span>
              <span v-if="searchParams.talentCompany" class="value">
                <strong>{{ searchParams.talentCompany }}</strong>
              </span>
              <span v-else class="value-empty">空</span>
            </span>

            <span class="result-item">
              <span class="label">成果名称：</span>
              <span v-if="searchParams.fruitName" class="value">
                <strong>{{ searchParams.fruitName }}</strong>
              </span>
              <span v-else class="value-empty">空</span>
            </span>

            <span class="result-item">
              <span class="label">合作次数：</span>
              <span v-if="searchParams.coMinNum && searchParams.coMaxNum" class="value">
                <strong>{{ searchParams.coMinNum }} - {{ searchParams.coMaxNum }}</strong>
              </span>
              <span v-else-if="searchParams.coMinNum" class="value">
                <strong>≥{{ searchParams.coMinNum }}</strong>
              </span>
              <span v-else-if="searchParams.coMaxNum" class="value">
                <strong>≤{{ searchParams.coMaxNum }}</strong>
              </span>
              <span v-else class="value-empty">空</span>
            </span>
          </div>
        </template>
      </div>
      <div style="padding-top: 15px;">统计时间：{{currentDate}}</div>
      <div style="padding-top: 15px;">总计专家数量：{{talentStatisticsDataObj.allTalentCount}}
        <a-button type="primary" style="margin-left: 20px;" @click="downloadExcel">下载</a-button>
      </div>
      <a-divider/>
      <a-spin :spinning="!isHaveNumData">
      </a-spin>
      <div v-show="talentStatisticsDataObj && talentStatisticsDataObj.companyCount.length>0">
        <div ref="groupCompanyCharts" style=" height: 350px; width: 100%;"></div>
      </div>
      <div v-show="talentStatisticsDataObj && talentStatisticsDataObj.cooNumCount.length>0">
        <div ref="groupCooNumCountCharts" style=" height: 350px; width: 100%;"></div>
      </div>
      <div v-show="talentStatisticsDataObj && talentStatisticsDataObj.jobLevelCount.length>0">
        <div ref="groupJobLevelCountCharts" style=" height: 350px; width: 100%;"></div>
      </div>
      <div v-show="talentStatisticsDataObj && talentStatisticsDataObj.jobTitleCount.length>0">
        <div ref="groupJobTitleCountCharts" style=" height: 350px; width: 100%;"></div>
      </div>
      <div v-show="talentStatisticsDataObj && talentStatisticsDataObj.researchFieldCount.length>0">
        <div ref="groupResearchFieldCountCharts" style=" height: 350px; width: 100%;"></div>
      </div>
    </a-modal>

    <a-drawer placement="right" width="1200" :maskClosable="false" @close="onClose" :visible="showFruitModal"
              title="查看成果">
      <talentFruit :talentId="talentId" v-if="showFruitModal" />
    </a-drawer>

    <a-drawer placement="right" width="1200" @close="onCloseStandard"  :visible="standardModal"
              title="查看数据标准">
      <EsDsTableManage />
    </a-drawer>

    <a-drawer placement="right" width="1200" @close="onCloseEvalIndex"  :visible="evalIndexModal"
              title="查看指标管理">
      <EsEvaIndexManage />
    </a-drawer>

    <a-drawer placement="right" width="1200" @close="onCloseChatModal" :visible="chartTalentModal"
              title="查看专家">
      <div style="margin-bottom: 10px; text-align: right;">
        <a-button type="primary" style="cursor: pointer;" @click="downloadExcel">下载</a-button>
      </div>
      <!-- 列表展示 -->
      <a-table :columns="chatColumns" :dataSource="chatDataSource" :key="tableKey" :pagination="false">
      </a-table>
      <br />
      <!-- 分页器 -->
      <a-pagination :show-total="total => `共${chatTotal}条`" :total="chatTotal" :current="chatPagination.current"
                    :pageSize="chatPagination.pageSize" @change="handlePaginationChange" />
    </a-drawer>

    <a-modal :width="600" v-model="importModal" title="导入" :mask-closable="false" :footer="null">
      <a-button icon="download" @click="downloadTemplate"> 下载模板</a-button>&nbsp;&nbsp;&nbsp;
      <a-upload
        name="file"
        :remove="handleTalentRemove"
        :beforeUpload="TalentBeforeUpload"
        :showUploadList="{ showDownloadIcon: true, showRemoveIcon: true }"
        :fileList="fkFileList"
      >
        <a-button icon="plus"> 导入专家</a-button>
      </a-upload>
      <a-button
        type="primary"
        :disabled="fkFileList.length === 0"
        :loading="fkLoading"
        style="margin-top: 16px"
        @click="importTalentExcel"
      >
        {{ fkLoading ? '上传中...' : '开始上传' }}
      </a-button>
    </a-modal>

  </div>
</template>

<script>
import { commonPostAction, postAction, uploadAction } from '@/api/esManage'
import TalentFruit from './EsTalentFruitManage.vue'
import TalentChart from './EsTalentChart.vue'
import Setting from '@/setting'
import * as echarts from 'echarts'
import { downFile } from '@api/manage'
import EsDsTableManage from '../../es/data_standard/EsDsTableManage.vue'
import EsEvaIndexManage from '../../es/eva-index/EsEvaIndexManage.vue'

export default {
  components: {
    TalentFruit,
    TalentChart,
    EsDsTableManage,
    EsEvaIndexManage
  },
  data() {
    return {
      searchForm: null,
      searchParams: {
        talentRealName: '',
        talentAllPhoneNumber: ''
      },
      tableKey: '',
      dataSource: [],
      // 选中的行
      selectedRows: [],
      selectedRowKeys: [],
      fieldsArr: ["碳达峰碳中和研究", "新型电力系统研究", "能源电力战略规划研究", "能源电力供需研究", "能源电力体制改革与电力市场研究", "能源电力数字经济研究",
        "企业战略规划研究", "企业经营与财务研究", "企业运营管理研究", "企业治理与风控合规研究", "品牌文化与社会责任研究", "数据、模型工具及实验室"],
      columns: [
        {
          title: '序号',
          dataIndex: 'key',
          key: 'key',
          align: 'center',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`//此处为重点
        },
        {
          title: '专家姓名',
          dataIndex: 'talentRealName',
          width: '10%',
        },
        {
          title: '工作单位',
          dataIndex: 'talentCompany',
          key: 'talentCompany',
          ellipsis: true,
        },
        {
          title: '职称',
          width: 100,
          dataIndex: 'talentJobTitle',
          customRender: (text, record) => {
            const value = record.talentJobTitle;
            return value === '其他' || value === null || value === undefined ? '' : value;
          }
        },
        {
          title: '职务',
          width: 120,
          dataIndex: 'talentJobLevel',
          customRender: (text, record) => {
            const value = record.talentJobLevel;
            return value === '其他' || value === null || value === undefined ? '' : value;
          },
          ellipsis: true,
        },
        // {
        //   title: '手机号码',
        //   dataIndex: 'talentAllPhoneNumber',
        //   key: 'talentAllPhoneNumber',
        //   ellipsis: true,
        //   width: '10%'
        // },
        {
          title: '合作次数',
          width: 100,
          dataIndex: 'talentCooperationNum',
          key: 'talentCooperationNum',
        },
        {
          title: '研究领域',
          dataIndex: 'talentGwFields',
          key: 'talentGwFields',
          ellipsis: true,
        },
        {
            title: '成果数量',
            width: 100,
            dataIndex: 'talentFruitCount',
            key: 'talentFruitCount',
            scopedSlots: {customRender: "talentFruitCount"},
        },
        // 其他列配置
        // ...
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      imageUrl: '',
      loading: false,
      total: 0,
      pagination: {
        current: 1,
        pageSize: 10
      },
      modalForm: null,
      modal: {
        visible: false,
        title: '',
        record: null,
        formData: {
          talentCooperationNum: 1
        }
      },
      mergeModal: {
        visible: false,
        title: '合并专家',
        record: null,
        formData: {
          mergeSelectedVal: '',
          waitMergeData: []
        }
      },
      mergeLoading: false,
      showFruitModal: false,
      talentId: null,
      importModal: false,
      fkFileList: [],
      fkLoading: false,
      fileList: [],
      showChartForm: false,
      isHaveNumData: false,
      talentNumResultData: [],
      currentDate: '',
      talentStatisticsDataObj: {
        companyCount: [],
        cooNumCount: [],
        jobLevelCount: [],
        jobTitleCount: [],
        researchFieldCount: [],
      },
      chartTalentModal: false,
      chatDataSource: [],
      chatTotal: 0,
      chatPagination: {
        current: 1,
        pageSize: 10
      },
      chatColumns: [
        {
          title: '序号',
          dataIndex: 'key',
          key: 'key',
          align: 'center',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`//此处为重点
        },
        {
          title: '专家姓名',
          dataIndex: 'talentRealName',
          width: '10%',
        },
        {
          title: '工作单位',
          dataIndex: 'talentCompany',
          key: 'talentCompany',
          ellipsis: true,
        },
        {
          title: '职称',
          width: 100,
          dataIndex: 'talentJobTitle',
          customRender: (text,record) => `${record.talentJobTitle  == '其他' ? '' : record.talentJobTitle }`
        },
        {
          title: '职务',
          width: 120,
          dataIndex: 'talentJobLevel',
          customRender: (text,record) => `${record.talentJobLevel  == '其他' ? '' : record.talentJobLevel }`,
          ellipsis: true,
        },
        {
          title: '合作次数',
          width: 100,
          dataIndex: 'talentCooperationNum',
          key: 'talentCooperationNum',
        },
        {
          title: '研究领域',
          dataIndex: 'talentGwFields',
          key: 'talentGwFields',
          ellipsis: true,
        }
      ],
      chatSelectedIds: [],
      standardModal: false,
      evalIndexModal: false
    }
  },
  methods: {
    search() {
      this.pagination.current = 1
      this.selectedRows = []
      this.selectedRowKeys = []
      this.fetchData()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      console.log('选中的行:', selectedRows)
    },
    reset() {
      this.searchParams = {}
      this.pagination = {
        current: 1,
        pageSize: 10
      }
      this.fetchData()
    },
    fetchData() {
      this.dataSource = []
      this.loading = true
      let url = '/talents/manage/pageList'
      let that = this
      let obj = {
        ...this.searchParams,
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize
      }
      this.mergeModal.formData.waitMergeData = []
      this.mergeModal.formData.mergeSelectedVal = ''
      this.tableKey = Math.random()
      postAction(url, obj).then(res => {
        if (res.data.success) {
          that.dataSource = res.data.result.records
          that.total = parseInt(res.data.result.total)
          this.loading = false
        }
      }).catch(err => {
        console.log(err)
        this.loading = false
      })
    },
    handlePaginationChange(page, pageSize) {
      this.pagination.current = page
      this.pagination.pageSize = pageSize
      this.fetchData()
    },
    showImportModal() {
      this.importModal = true
    },
    edit(record) {
      this.imageUrl = ''
      this.imageUrl = record.talentPhoto
      this.showModal('edit', JSON.parse(JSON.stringify(record)))
    },
    showModal(type, record) {
      this.modal.type = type
      this.modal.title = type === 'add' ? '新增专家' : '编辑专家'
      if (type != 'add') {
        this.modal.formData = record
      } else {
        this.modal.formData = {talentCooperationNum: 1}
      }
      this.modal.visible = true
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('只能上传 JPG/PNG 格式的图片！')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB！')
      }
      return false
    },
    handleChange(info) {
      this.$message.loading(`正在上传...`)
      const file = info.file
      if (file) {
        this.convertToBase64(info.file)
      } else {
        this.$message.error('未获取到有效的文件对象')
      }
    },
    convertToBase64(file) {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        this.imageUrl = reader.result
        console.log('Base64 图片:', this.imageUrl)
        this.$message.success(`上传成功`)
        this.modal.formData.talentPhoto = this.imageUrl
      }
      reader.onerror = () => {
        this.$message.error('图片转换为 Base64 失败')
      }
    },
    async handleOk() {
      if (!this.modal.formData.talentRealName) {
        this.$message.error('请输入专家姓名！')
        return
      }
      if (!this.modal.formData.talentCompany) {
        this.$message.error('请输入专家单位！')
        return
      }
      let url = '/talents/manage/saveOrUpdate'
      let that = this

      postAction(url, this.modal.formData).then(res => {
        if (res.data.success) {
          that.$message.success('操作成功')
          this.modal.visible = false
          this.fetchData()
        }
      }).catch(err => {
        console.log(err)
      })
    },
    handleCancel() {
      this.modal.visible = false
    },
    downloadTemplate() {
      let a = document.createElement('a')
      a.download = '专家数据模板.xls'
      // a.href = '/static/template/talent.xls'
      a.href = `${window.location.origin}/${Setting.publicPath}/static/template/talent.xls`;
      a.click()
    },
    handleTalentRemove(file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fkFileList = newFileList
    },
    TalentBeforeUpload(file) {
      if (
        file.name.substr(file.name.length - 3).toLowerCase() != 'xls' &&
        file.name.substr(file.name.length - 4).toLowerCase() != 'xlsx'
      ) {
        this.$message.warning('只能上传xls、xlsx文件!')
      } else {
        this.fkFileList = [...this.fkFileList, file]
      }
      return false
    },
    importTalentExcel() {
      this.fkLoading = true
      let formData = new FormData()
      this.fkFileList.forEach(file => {
        formData.append('file', file)
      })
      let url = '/talents/manage/importTalentDataExcel'
      uploadAction(url, formData).then(res => {
        if (res.data.success) {
          this.fkLoading = false
          this.fkFileList = []
          this.$message.success('文件导入成功!')
        } else {
          this.fkLoading = false
          this.$message.error('文件导入失败!')
        }
      }).catch(err => {
        console.log(err)
        this.fkLoading = false
        this.$message.error('文件导入失败!')
      })
    },
    merge() {
      let isAllSame = true
      if (this.selectedRows.length < 2) {
        this.$message.error('请至少选择 2 条数据！')
        return
      }
      const firstRealName = this.selectedRows[0].realName
      for (const item of this.selectedRows) {
        if (item.realName !== firstRealName) {
          isAllSame = false
          this.$message.error('选择的姓名有不一致，请检查！')
          return
        }
      }
      this.mergeModal.visible = true
    },
    handleMergeChange(value) {
      console.log(`selected ${value}`)
      this.mergeModal.formData.waitMergeData = this.selectedRows.map(item => {
        return item.id
      })
      this.mergeModal.formData.mergeSelectedVal = value
    },
    async handleMergeOk() {
      let url = '/talents/manage/mergeTalent'
      let that = this
      that.mergeModal.visible = false
      this.mergeLoading = true

      postAction(url, this.mergeModal.formData).then(res => {
        if (res.data.success) {
          that.$message.success('操作成功')
          that.mergeLoading = false
          that.fetchData()
        }
      }).catch(err => {
        console.log(err)
      })
    },
    handleMergeCancel() {
      this.mergeModal.visible = false
    },
    remove(record) {
      try {
        let url = '/talents/manage/delete'
        let that = this
        postAction(url, record).then(res => {
          if (res.data.success) {
            that.$message.success('操作成功')
            this.modal.visible = false
            this.fetchData()
          }
        }).catch(err => {
          console.log(err)
        })
      } catch (error) {
        console.error('Error deleting record:', error)
      }
    },
    lookFruit(record) {
      this.showFruitModal = true
      this.talentId = record.id
    },
    onClose() {
      this.showFruitModal = false
    },
    onCloseStandard() {
      this.standardModal = false
    },
    onCloseEvalIndex() {
      this.evalIndexModal = false
    },
    onCloseChatModal() {
      this.chartTalentModal = false
      this.searchParams.ids = [];
    },
    showChart() {
      this.showChartForm = !this.showChartForm;
      this.isHaveNumData = false;
      let url = '/talents/manage/getTalentChart'
      postAction(url, this.searchParams).then(res => {
        if (res.data.success) {
          this.isHaveNumData = true;
          this.talentStatisticsDataObj = res.data.result;
          this.buildRankTalentChart(this.$refs.groupCompanyCharts, this.talentStatisticsDataObj.companyCount, "专家单位统计");
          this.buildRankTalentChart(this.$refs.groupCooNumCountCharts, this.talentStatisticsDataObj.cooNumCount, "专家合作次数统计");
          this.buildRankTalentChart(this.$refs.groupJobLevelCountCharts, this.talentStatisticsDataObj.jobLevelCount, "专家职务统计");
          this.buildRankTalentChart(this.$refs.groupJobTitleCountCharts, this.talentStatisticsDataObj.jobTitleCount, "专家职称统计");
          this.buildRankTalentChart(this.$refs.groupResearchFieldCountCharts, this.talentStatisticsDataObj.researchFieldCount, "专家领域统计");
        }
      }).catch(err => {
        console.log(err)
      })
    },
    buildRankTalentChart(chartDom, data, title) {
      if (!chartDom) return;

      const fruitChart = echarts.getInstanceByDom(chartDom) || echarts.init(chartDom);

      // let fruitChart = echarts.init(this.$refs.groupRankCharts);
      let xAxisData = data.map(item => {
        return item.name
      })
      // 构建 series 数据并附加 ids 信息
      let seriesData = data.map(item => {
        return {
          value: item.count,
          name: item.name,
          ids: item.ids // 将 ids 添加到每个数据项中
        };
      });

      // 解绑之前的 click 事件，避免重复绑定
      fruitChart.off('click');

      fruitChart.setOption({
        title: {
          text: title
        },
        grid: {
          bottom: '40%'
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          axisLabel: {
            inside: false,
            color: '#000',
            interval: 0,
            formatter: function (value) {
              return value.split('').join('\n')
            }
          },
          axisTick: {
            show: false
          },
          axisLine: {
            show: false
          },
          z: 10
        },
        dataZoom: [
          {
            type: 'inside'
          }
        ],
        yAxis: {
          type: 'value',
          minInterval: 1
        },
        tooltip: {
          alwaysShowContent: true,
          trigger: 'axis',
          extraCssText: 'z-index: 7',
          backgroundColor: '#FFFFFF',
          textStyle: {
            color: '#3c3520'
          }
        },
        series: [
          {
            data: seriesData,
            type: 'bar',
            showBackground: true,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {offset: 0, color: '#79DBBA'},
                {offset: 0.5, color: '#3FA598'},
                {offset: 1, color: '#008080'}
              ])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {offset: 0, color: '#79DBBA'},
                  {offset: 0.5, color: '#3FA598'},
                  {offset: 1, color: '#008080'}
                ])
              }
            },
          }
        ]
      }, true);

      // 添加点击事件监听器
      fruitChart.on('click', params => {
        if (params.data && params.data.ids) {
          this.chartTalentModal = true;
          console.log('点击的柱状图 ids:', params.data.ids);
          this.chatSelectedIds = params.data.ids.split(",");

          this.chatDataSource = []
          let url = '/talents/manage/pageList'
          let that = this
          let obj = {
            idArr: params.data.ids.split(","),
            pageNo: this.chatPagination.current,
            pageSize: this.chatPagination.pageSize
          }
          postAction(url, obj).then(res => {
            if (res.data.success) {
              that.chatDataSource = res.data.result.records
              that.chatTotal = parseInt(res.data.result.total)
            }
          }).catch(err => {
            console.log(err)
          })
        } else {
          console.log('未找到 ids 信息');
          console.log(params);
        }
      });

      setTimeout(function () {
        fruitChart.resize();
      }, 10)
    },
    downloadExcel(){
      this.searchParams.idArr = this.chatSelectedIds;
      let url = '/es/talents/manage/exportTalentData'
      downFile(url, this.searchParams, "post").then(data => {
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
          let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.ms-excel'}))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', '专家信息导出数据.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
      })
    },
    showStandard() {
      // const routeUrl = this.$router.resolve({
      //   name: 'DataStandard',
      //   query: {}
      // });
      // window.open(routeUrl.href, '_blank');
      this.standardModal = true;
    },
    showEvaIndex() {
      this.evalIndexModal = true;
    }
  },
  created() {
    this.fetchData();

    const date = new Date()
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    this.currentDate = `${year}-${month}-${day}` // 格式: 2023-06-27
  }
}
</script>

<style scoped>
/* 样式 */
.avatar-uploader > .ant-upload {
  width: 100px;
  height: 100px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.iptN{
  text-align: center;
}
.search-result-card {
  padding: 10px;
  border: 1px solid #e5e5e5;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.result-item {
  margin-bottom: 8px;
  margin-right: 30px;
}

.label {
  color: #666;
  min-width: 80px;
}

.value {
  color: #333;
  font-weight: 500; /* 加强非空值的视觉差异 */
}

.value-empty {
  color: #999;
  font-style: italic;
}

strong {
  font-weight: bold;
}
</style>
